/*
 * =====================================================================================
 *
 *       Filename:  axismean.cpp
 *
 *    Description:  Returns the mean position of pixels by axis
 *
 *        Version:  1.0
 *        Created:  05/07/12 15:59:20
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Moos Hueting (mh), mooshueting@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <iostream>
#include <cv.h>
#include <highgui.h>

using namespace std;
using namespace cv;

float axismean(Mat src, char rowcol) {
    Size s = src.size();

    int minx = 1000;
    int maxx = 0;
    int miny = 1000;
    int maxy = 0;

    for (int i = 0; i < s.height; i++) {
        for (int j = 0; j < s.width; j++) {
            // if the current pixel is set
            if (src.at<unsigned char>(i, j) > 0) { 
                if (i < miny)
                    miny = i;
                if (i > maxy)
                    maxy = i;
                if (j < minx)
                    minx = j;
                if (j > maxx)
                    maxx = j;
            }
        }
    }
    
    if (rowcol == 0) {
    // row mean
        int rsSum = 0;
        int rowSum;

        for (int i=miny; i <= maxy; i++) {
            rowSum = 0;
            for (int j=minx; j <= maxx; j++) {
                if (src.at<unsigned char>(i,j) != 0)
                    rowSum++;
            }
            rsSum += rowSum * (i - miny);
        }
        return ((float)rsSum / countNonZero(src)) / (maxy - miny);
    } else {
    // column mean
        int csSum = 0;
        int colSum;

        for (int i=minx; i < maxx; i++) {
            colSum = 0;
            for (int j=miny; j < maxy; j++) {
                if (src.at<unsigned char>(j,i) != 0)
                    colSum++;
            }
            csSum += colSum * (i - minx);
        }
//        cout << (float)csSum / countNonZero(src) << endl;
        return ((float)csSum / countNonZero(src)) / (maxx - minx);
    }
}

//int main(int argc, char* argv[]) {
//    Mat image;
//
//    image = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
//    threshold(image, image, 100, 255, THRESH_BINARY);
//
//    cout << axismean(image, 0) << ", " << axismean(image, 1) << endl;
//}
